package com.tally.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.tally.server.dto.*;
import com.tally.server.service.CommentService;
import com.tally.server.service.LikesService;
import com.tally.server.service.MessageService;
import com.tally.server.service.PostService;
import com.tally.server.utils.ValidatorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * @Author: sy
 * @Date: 2020/11/13 20:13
 * @Description:
 */
@RestController
@RequestMapping("/post")
public class PostController extends BusinessController{

    private static final Logger logger = LoggerFactory.getLogger(PostController.class);
    public static final String BUSINESS_NAME = "文章";

    @Autowired
    private PostService postService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikesService likesService;

    @Autowired
    private MessageService messageService;

//    @Autowired
//    private

    /**
     * 列表查询
     * @param pageDTO
     * @return
     */
    @PostMapping("/list")
    public ResponseDTO list(@RequestBody PageDTO pageDTO){
        JSONObject loginUser = getLoginUser();
        postService.list(pageDTO, loginUser.getInteger("id"));
        return ResponseDTO.success(pageDTO);
    }

    /**
     * 保存，id有值时更新，无值时新增
     * @param postDTO
     * @return
     */
    @PostMapping("/save")
    public ResponseDTO save(@RequestBody PostDTO postDTO){
        // 保存校验
        ValidatorUtil.require(postDTO.getTitle(),"标题");
        ValidatorUtil.length(postDTO.getTitle(),"标题",1,16);

        postService.save(postDTO);
        return ResponseDTO.success(null);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public ResponseDTO delete(@PathVariable String id){
        postService.delete(id);
        commentService.deleteByPostId(id);
        likesService.deleteByPostId(id);
        messageService.deleteByPostId(id);
        return ResponseDTO.success(null);
    }

    @GetMapping("/detail/{id}")
    public ResponseDTO detail(@PathVariable String id) {
        ValidatorUtil.require(id, "文章id");
        PostDTO postDTO = postService.getById(id);
        return ResponseDTO.success(postDTO);
    }

    @GetMapping("/comments/{id}")
    public ResponseDTO comments(@PathVariable String id) {
        ValidatorUtil.require(id, "文章id");
        Integer commentCount = postService.getComments(id);
        return ResponseDTO.success(commentCount);
    }

    @DeleteMapping("/comment/delete/{id}")
    public ResponseDTO deleteComment(@PathVariable Integer id) {
        commentService.delete(id);
        return ResponseDTO.success(null);
    }


    @PostMapping("/comment/publish")
    @Transactional
    public ResponseDTO publishComment(@RequestBody CommentDTO commentDTO) {
        // 保存校验
        ValidatorUtil.require(commentDTO.getContent(),"评论内容");
        ValidatorUtil.length(commentDTO.getContent(),"评论内容",1,128);
        commentService.save(commentDTO);
        // 文章增加评论数
        postService.addComments(commentDTO.getPostId());
        return ResponseDTO.success(null);
    }

    @GetMapping("/comment/commentList/{postId}")
    public ResponseDTO commentList(@PathVariable String postId) {
        ValidatorUtil.require(postId, "文章id");
        List<CommentDTO> commentDTOList = commentService.getByPostId(postId);
        return ResponseDTO.success(commentDTOList);
    }

    @PostMapping("/likes/like")
    @Transactional
    public ResponseDTO like(@RequestBody LikesDTO likesDTO) {
        // 记录点赞信息
        likesService.save(likesDTO);
        // 增加点赞数
        postService.addLikes(likesDTO.getPostId(), likesDTO.getLikeStatus());
        // 查询该文章的点赞信息
        List<LikesDTO> likesDTOList = likesService.getByPostId(likesDTO.getPostId());
        return ResponseDTO.success(likesDTOList);
    }

    @GetMapping("/likes/loadLikes/{postId}")
    public ResponseDTO loadLikes(@PathVariable String postId) {
        List<LikesDTO> likesDTOList = likesService.getByPostId(postId);
        return ResponseDTO.success(likesDTOList);
    }

    @GetMapping("/likes/getLikeStatus/{userId}/{postId}")
    public ResponseDTO getLikeStatus(@PathVariable Integer userId, @PathVariable String postId) {
        LikesDTO likesDTO = likesService.getByUserIdAndPostId(userId, postId);
        if (likesDTO == null) {
            return ResponseDTO.success(null);
        }
        return ResponseDTO.success(likesDTO.getLikeStatus());
    }

    @PostMapping("/search")
    public ResponseDTO searchPost(@RequestBody SearchPostPageDTO postPageDTO) throws IOException {
        JSONObject loginUser = getLoginUser();
        try {
            postService.searchPostWithEs(postPageDTO, loginUser.getInteger("id"));
        }catch(IOException e) {
            logger.info("ES 连接失败，使用MySQL查询");
            postService.searchPost(postPageDTO, loginUser.getInteger("id"));
        }
        return ResponseDTO.success(postPageDTO);
    }
}
